const express = require("express");
// 有什么难的，express, mysql, sequelize, zpqy, sequelize-cli 所有技术都只是我的工具而已，怕什么？
const { User } = require("../../models");
const { Op } = require("sequelize");
const { success, fail } = require("../../utils/response");
const {NotFound, BadRequest} = require('http-errors')
const bcrypt = require('bcrypt')
/**
 * 用户路由-管理后台
 * 1.分页查询 支持keywords查询
 * 2.查询所有，暂不需要
 * 3.用户详情
 * 4.增加用户
 * 5.删除用户
 * 6.修改用户
 */
const router = express.Router();
// 查询用户-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await User.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { username, nickname, email, pageNum, role, pageSize } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (username) {
    conditions.where.username = {
      [Op.like]: `%${username}%`,
    };
  }
  if (nickname) {
    conditions.where.nickname = {
      [Op.like]: `%${nickname}%`,
    };
  }
  if (email) {
    conditions.where.email = email;
  }
  if (role) {
    conditions.where.role = role;
  }
  return conditions;
}
// 查询用户-无分页
router.get("/all", async (req, res) => {
  try {
    const { keywords } = req.query;
    let where = {};

    if (keywords) {
      where.name = {
        [Op.like]: `%${keywords}%`,
      };
    }
    const raws = await User.findAll({ where });
    success(res, "获取成功", raws);
  } catch (error) {
    fail(res, error);
  }
});
// 查询用户详情
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw BadRequest('用户id不能为空')
    }
    const user = await User.findByPk(id);
    if (!user) {
      throw NotFound("未找到此用户");
    }
    success(res, "获取成功", user);
  } catch (error) {
    fail(res, error);
  }
});
// 增加用户
router.post("/", async (req, res) => {
  try {
    const param = filterParamByWhiteName(req);
    const user = await User.create(param);
    console.log("user", user);
    success(res, "success", user);
  } catch (error) {
    fail(res, error);
  }
});
// // 密码加密
// function encryptPwd(password) {
//   const hashedPwd = bcrypt.hashSync(password, 10)
//   console.log('hashedPwd',hashedPwd);
//   return hashedPwd
// }
// 修改用户
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    if(!id) {
      throw new BadRequest('id不能为空')
    }
    const param = filterParamByWhiteName(req);
    const [count] = await User.update(param, {
      where: {
        id,
      },
    });
    if (!count) {
      throw NotFound("未找到此用户");
    }
    success(res, "success", id);
  } catch (error) {
    fail(res, error);
  }
});
// 删除用户
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.destroy({
      where: { id },
    });
    if (!user) {
      throw NotFound("未找到此用户");
    }
    success(res, "success");
  } catch (error) {
    fail(res, error);
  }
});
// 拿到需要的请求参数 - 用于新增、编辑、查询条件
function filterParamByWhiteName(req) {
  const { username, nickname, password, introduce, email, avatar, role, sex, phone, company } = req.body;
  return {
    username,
    nickname,
    password,
    introduce,
    email,
    avatar,
    role,
    sex,
    phone,
    company,
  };
}

module.exports = router;
